<template>
  <el-dialog :title="'手动签到'" :visible.sync="visible" width="600px" :close-on-click-modal="false" append-to-body>
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right">
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="选择老师" prop="teacherId">
            <el-select v-model="dataForm.teacherId" placeholder="请选择老师" filterable clearable :style="{ width: '100%' }" @change="onTeacherChange">
              <el-option v-for="item in teacherOptions" :key="item.id" :label="item.teacherName" :value="item.id">
                <span style="float: left">{{ item.teacherName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.idCard }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到日期" prop="signDate">
            <el-date-picker v-model="dataForm.signDate" type="date" placeholder="请选择签到日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到时段" prop="period">
            <el-select v-model="dataForm.period" placeholder="请选择时段" :style="{ width: '100%' }" @change="onPeriodChange">
              <el-option label="上午" value="AM" />
              <el-option label="下午" value="PM" />
              <el-option label="晚上" value="EVE" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="请选择状态" :style="{ width: '100%' }">
              <el-option label="正常签到" value="Normal" />
              <el-option label="迟到" value="Late" />
              <el-option label="请假" value="Leave" />
              <el-option label="早退" value="EarlyLeave" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到时间" prop="signTime">
            <el-date-picker 
              v-model="dataForm.signTime" 
              type="datetime" 
              placeholder="请选择签到时间" 
              format="yyyy-MM-dd HH:mm:ss" 
              value-format="yyyy-MM-dd HH:mm:ss" 
              :style="{ width: '100%' }"
              :picker-options="timePickerOptions" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入备注" :rows="3" maxlength="500" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { manualSignIn, getTrainSignRecordList } from '@/api/campus/trainSignRecord'
import { getTrainParticipantList } from '@/api/campus/trainOrderItem'
import signTimeValidator from '@/utils/signTimeValidator'
import auditLogger from '@/utils/auditLogger'

export default {
  data() {
    return {
      visible: false,
      loading: false,
      trainId: '',
      dataForm: {
        trainId: '',
        teacherId: '',
        signDate: '',
        period: '',
        status: 'Normal',
        signTime: '',
        remark: ''
      },
      dataRule: {
        teacherId: [{ required: true, message: '请选择老师', trigger: 'change' }],
        signDate: [{ required: true, message: '请选择签到日期', trigger: 'change' }],
        period: [{ required: true, message: '请选择签到时段', trigger: 'change' }],
        status: [{ required: true, message: '请选择签到状态', trigger: 'change' }],
        signTime: [
          { required: true, message: '请选择签到时间', trigger: 'change' },
          { validator: this.validateSignTime, trigger: 'change' }
        ]
      },
      teacherOptions: [],
      timePickerOptions: {
        disabledDate: (time) => {
          // 不能选择未来日期
          return time.getTime() > Date.now()
        }
      }
    }
  },
  watch: {
    'dataForm.signDate'() {
      if (this.dataForm.signDate && this.dataForm.period && this.trainId) {
        this.getTeacherList()
        this.dataForm.teacherId = '' // 清空已选择的老师
      }
    },
    'dataForm.period'() {
      if (this.dataForm.signDate && this.dataForm.period && this.trainId) {
        this.getTeacherList()
        this.dataForm.teacherId = '' // 清空已选择的老师
      }
    }
  },
  methods: {
    init(trainId) {
      this.trainId = trainId
      this.dataForm.trainId = trainId
      this.visible = true
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields()
        // 设置默认值
        this.setDefaultValues()
        // 设置默认值后再加载可用老师
        if (this.dataForm.signDate && this.dataForm.period) {
          this.getTeacherList()
        }
      })
    },
    setDefaultValues() {
      const now = this.$moment()
      this.dataForm.signDate = now.format('YYYY-MM-DD')
      
      // 使用智能默认时段
      this.dataForm.period = signTimeValidator.getSmartDefaultPeriod()
      
      // 使用智能默认时间
      this.dataForm.signTime = signTimeValidator.getSmartDefaultTime(
        this.dataForm.period, 
        this.dataForm.signDate
      )
      
      // 默认状态为正常签到
      this.dataForm.status = 'Normal'
    },
    async getTeacherList() {
      if (!this.dataForm.signDate || !this.dataForm.period) {
        // 如果没有选择签到日期和时段，暂不加载老师列表
        this.teacherOptions = []
        return
      }
      
      try {
        // 获取所有参训老师
        const participantRes = await getTrainParticipantList(this.trainId)
        const allTeachers = participantRes.data || []
        
        if (allTeachers.length === 0) {
          this.teacherOptions = []
          this.$message.info('该师训暂无参训老师')
          return
        }
        
        // 获取已签到的老师列表
        const signRecordRes = await getTrainSignRecordList({
          trainId: this.trainId,
          signDate: this.dataForm.signDate,
          period: this.dataForm.period,
          pageIndex: 1,
          pageSize: 1000
        })
        
        // 处理API返回的数据结构，可能是分页格式
        let signedTeachers = []
        if (signRecordRes.data) {
          if (Array.isArray(signRecordRes.data)) {
            signedTeachers = signRecordRes.data
          } else if (signRecordRes.data.list && Array.isArray(signRecordRes.data.list)) {
            signedTeachers = signRecordRes.data.list
          } else if (signRecordRes.data.records && Array.isArray(signRecordRes.data.records)) {
            signedTeachers = signRecordRes.data.records
          }
        }
        
        const signedTeacherIds = signedTeachers.map(record => record.teacherId || record.id)
        
        // 过滤掉已签到的老师
        const availableTeachers = allTeachers.filter(teacher => 
          !signedTeacherIds.includes(teacher.teacherId || teacher.id)
        )
        
        this.teacherOptions = availableTeachers
        
        if (availableTeachers.length === 0) {
          this.$message.info('该时段所有老师都已签到')
        }
        
      } catch (err) {
        console.error('获取参训老师列表失败:', err)
        this.$message.error('获取参训老师列表失败，请重试')
        this.teacherOptions = []
      }
    },
    onTeacherChange(teacherId) {
      // 选择老师后可以自动填充一些信息
      const teacher = this.teacherOptions.find(item => item.id === teacherId)
      if (teacher) {
        // 可以在这里设置一些默认值
        console.log('选择老师:', teacher.teacherName)
      }
    },
    onPeriodChange(period) {
      // 根据时段智能调整签到时间
      if (this.dataForm.signDate) {
        this.dataForm.signTime = signTimeValidator.getSmartDefaultTime(
          period, 
          this.dataForm.signDate
        )
      }
    },
    async validateSignTime(rule, value, callback) {
      if (!value || !this.dataForm.signDate || !this.dataForm.period) {
        callback()
        return
      }
      
      try {
        // 使用统一的验证工具进行验证
        const result = await signTimeValidator.validateSignTime({
          trainId: this.trainId,
          signTime: value,
          signDate: this.dataForm.signDate,
          period: this.dataForm.period,
          teacherId: this.dataForm.teacherId
        })
        
        if (!result.valid) {
          callback(new Error(result.message))
          return
        }
        
        // 如果检测到迟到，给出提示但不阻止提交
        if (result.isLate) {
          this.$message.warning(`注意：当前签到时间将被标记为迟到（迟到${result.lateMinutes}分钟）`)
        }
        
        callback()
      } catch (error) {
        console.error('签到时间验证失败:', error)
        // 如果服务端验证失败，回退到基础验证
        const basicResult = signTimeValidator.validateBasicRules(
          value, 
          this.dataForm.signDate, 
          this.dataForm.period
        )
        
        if (!basicResult.valid) {
          callback(new Error(basicResult.message))
        } else {
          callback()
        }
      }
    },
    dataFormSubmit() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          // 获取选中的老师信息
          const teacher = this.teacherOptions.find(item => item.id === this.dataForm.teacherId)
          const teacherName = teacher ? teacher.teacherName : '未知老师'
          
          // 确认对话框
          this.$confirm(
            `确认为老师"${teacherName}"进行手动签到吗？\n` +
            `签到日期：${this.dataForm.signDate}\n` +
            `签到时段：${this.getPeriodLabel(this.dataForm.period)}\n` +
            `签到状态：${this.getStatusLabel(this.dataForm.status)}\n` +
            `签到时间：${this.dataForm.signTime}`,
            '确认手动签到',
            {
              confirmButtonText: '确定签到',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: false
            }
          ).then(() => {
            this.loading = true
            const submitData = {
              ...this.dataForm,
              method: 'MANUAL' // 手动签到
            }
            
            manualSignIn(submitData).then(async res => {
              // 记录审计日志
              try {
                const logData = auditLogger.createManualSignLogData(
                  teacher,
                  this.dataForm,
                  '手动签到操作'
                )
                await auditLogger.logOperation(logData, true)
              } catch (logError) {
                console.warn('审计日志记录失败:', logError)
              }
              
              this.$message({
                message: res.msg || `${teacherName} 手动签到成功`,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.loading = false
                  this.$emit('refresh')
                }
              })
            }).catch(async (error) => {
              // 记录失败日志
              try {
                const logData = auditLogger.createManualSignLogData(
                  teacher,
                  this.dataForm,
                  '手动签到操作失败'
                )
                await auditLogger.logFailure(logData, error)
              } catch (logError) {
                console.warn('失败日志记录失败:', logError)
              }
              
              this.loading = false
            })
          })
        }
      })
    },
    getPeriodLabel(period) {
      return signTimeValidator.getPeriodLabel(period)
    },
    getStatusLabel(status) {
      return signTimeValidator.getStatusLabel(status)
    }
  }
}
</script>